package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.*;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;
    @DubboReference
    private FriendApi friendApi;
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private VisitorsApi visitorsApi;


    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        } else {
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo, vo); //copy同名同类型的属性

        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    //客户端喜欢数据统计
    public CountVo counts() {
        return userLikeApi.counts(UserHolder.getUserId());
    }

    //互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
    public PageResult friendsType(Integer page, Integer pagesize, String nickname, Integer type) {
        if (type == 1) {
            //互相关注
            return getPageResult1(page, pagesize, nickname);
        } else if (type == 2) {
            //喜欢列表
            return getPageResult2(page, pagesize, nickname);
        } else if (type == 3) {
            //粉丝列表
            return getPageResult3(page, pagesize, nickname);
        } else {
            //谁看过我  访客列表
            return getPageResult4(page, pagesize);
        }

    }

    private PageResult getPageResult4(Integer page, Integer pagesize) {
        //调用api查看所有访客列表
        List<Visitors> list = visitorsApi.queryMyVisitors(UserHolder.getUserId(), page, pagesize);
        //提取访客id
        List<Long> visitorUserId = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(visitorUserId, null);

        //构造vo对象
        ArrayList<UserTypeVo> vos = new ArrayList<>();
        for (Visitors visitors : list) {
            UserTypeVo vo = new UserTypeVo();
            UserInfo userInfo = map.get(visitors.getVisitorUserId());
            if (userInfo != null) {
                BeanUtils.copyProperties(userInfo, vo);
                Integer matchRate = visitors.getScore().intValue();
                //设置匹配度
                vo.setMatchRate(Integer.valueOf(matchRate));
            }
            vos.add(vo);
        }

        //向redis设置用户查看访问时间
        String key = Constants.VISITORS_USER;
        String hashKey = String.valueOf(UserHolder.getUserId());
        redisTemplate.opsForHash().put(key,hashKey,Long.toString(System.currentTimeMillis()));
        return new PageResult(page, pagesize, 0l, vos);
    }

    //粉丝列表
    private PageResult getPageResult3(Integer page, Integer pagesize, String nickname) {
        List<Long> userIds = userLikeApi.fans(UserHolder.getUserId(), page, pagesize);
        if (CollUtil.isEmpty(userIds)) {
            return new PageResult();
        }
        //查询粉丝用户详情
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        Map<Long, UserInfo> fansMap = userInfoApi.findbyIds(userIds, userInfo);
        //查询用户喜欢数据
        Map<Long, UserLike> likeMap = userLikeApi.userLike(UserHolder.getUserId());
        List<UserTypeVo> vos = new ArrayList<>();
        for (Long userId : userIds) {
            UserTypeVo vo = new UserTypeVo();
            UserInfo info = fansMap.get(userId);
            UserLike userLike = likeMap.get(userId);

            if (userLike == null) {
                vo.setAlreadyLove(false);
            } else {
                vo.setAlreadyLove(userLike.getIsLike());
            }

            if (info != null) {
                BeanUtils.copyProperties(info, vo);
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0l, vos);
    }

    //喜欢列表
    private PageResult getPageResult2(Integer page, Integer pagesize, String nickname) {
        //从redis中获取用户喜欢的用户id集合
        Set<String> members = redisTemplate.opsForSet().members(Constants.USER_LIKE_KEY + UserHolder.getUserId());
        //如果是空直接返回
        if (CollUtil.isEmpty(members)) {
            return new PageResult();
        }
        //set转换成list集合并分页
        List<Long> userIds = members.stream().skip((page - 1) * pagesize).limit(pagesize).map(e -> Long.valueOf(e)).collect(Collectors.toList());
        //查询用户详情
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, userInfo);
        List<UserInfo> vos = new ArrayList<>();
        for (String userId : members) {   //此处必须用刚从redis取出来的set集合     list集合分页完数据不完整
            UserInfo info = map.get(Long.valueOf(userId));
            if (info != null) {
                vos.add(info);
            }
        }

        return new PageResult(page, pagesize, 0l, vos);
    }

    //相互喜欢
    private PageResult getPageResult1(Integer page, Integer pagesize, String nickname) {
        //调用api查询当前用户的好友数据
        List<Friend> list = friendApi.findUserId(UserHolder.getUserId(), page, pagesize);
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //提取数据列表中的好友id
        List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        //调用userInfoApi查询好友详细信息
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, userInfo);
        //构造对象
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo1 = map.get(friend.getFriendId());
            if (userInfo1 != null) {
                ContactVo vo = ContactVo.init(userInfo1);
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0l, vos);
    }


}
